@extends('Admin.layout')
@section('header')
    <link rel="stylesheet" href="https://unpkg.com/codemirror@5.65.14/lib/codemirror.css">
    <link rel="stylesheet" href="https://unpkg.com/codemirror@5.65.14/theme/material.css">
    <link rel="stylesheet" href="https://unpkg.com/codemirror@5.65.14/addon/dialog/dialog.css">
    <script src="https://unpkg.com/codemirror@5.65.14/lib/codemirror.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/addon/dialog/dialog.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/addon/edit/closebrackets.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/addon/search/jump-to-line.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/addon/search/searchcursor.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/addon/search/search.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/mode/sql/sql.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/mode/clike/clike.js"></script>
    <script src="https://unpkg.com/codemirror@5.65.14/mode/php/php.js"></script>
@endsection
@section('main')
    <el-form :inline="true">
        <el-form-item :label-width="120" label="模块：">
            <el-select
                    v-model="module"
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="Choose tags for your article"
                    style="width: 240px"
                    @change="moduleChange"
            >
                <el-option
                        v-for="item in modules"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="makeApi()">生成</el-button>
            <el-button type="primary" @click="makeApi('c')">预览Controller</el-button>
            <el-button type="primary" @click="makeApi('s')">预览Service</el-button>
        </el-form-item>
    </el-form>
    <el-row>
        <el-col :span="6" style="height: 650px">
            <el-tree-v2 :data="files" :props="fileProps" :highlight-current="true" :height="600" @node-click="nodeClick">
                <template #default="{ node, data}">
                    <span v-if="data.type == 'dir'" style="color: #E6A23C"><el-icon><Folder-Opened /></el-icon></span>
                    <span v-else style="color:#409EFF;"><el-icon><Document /></el-icon></span>
                    <span style="margin-left: 3px">@{{ node.label }}</span>
                </template>
            </el-tree-v2>
        </el-col>
        <el-col :span="6">
            <el-form style="padding-right: 5px;box-sizing: border-box">
                <el-form-item :label-width="90" label="查询数据表:">
                    <el-autocomplete value-key="TABLE_NAME" clearable @select="tableSelected"
                                     :fetch-suggestions="tableQuerySearch" v-model="updateData.table" placeholder="表名">
                        <template #default="{ item }">
                            @{{item.TABLE_NAME}} @{{item.TABLE_COMMENT}}
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item :label-width="90" label="Controller:">
                    <el-input v-model="updateData.controller" readonly="" placeholder="文件名" clearable></el-input>
                </el-form-item>
                <el-form-item :label-width="90" label="Service:">
                    <el-input v-model="updateData.service" readonly="" placeholder="文件名" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="updateData.function" @change="makeMethodName">
                        <el-radio key="single" value="single" label="获取单条">获取单条</el-radio>
                        <el-radio key="multiple" value="multiple" label="获取多条">获取多条</el-radio>
                        <el-radio key="auth" value="save" label="保存数据">保存数据</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label-width="90" label="method名:">
                    <el-input v-model="updateData.method" placeholder="method名" clearable></el-input>
                </el-form-item>
                <el-form-item v-if="fields.length > 0">
                    <el-checkbox
                            v-model="checkAll"
                            :indeterminate="isIndeterminate"
                            @change="handleCheckAllChange"
                    >全部</el-checkbox>
                </el-form-item>
                <el-form-item v-if="fields.length > 0" style="height: 350px;overflow: auto;display: block">
                    <el-checkbox-group v-model="updateData.fields"  @change="handleCheckedCitiesChange">
                        <el-checkbox style="display: block" v-for="field in fields" :key="field.COLUMN_COMMENT" :value="field.COLUMN_NAME" :label="field.COLUMN_COMMENT">
                            @{{ field.COLUMN_COMMENT ? field.COLUMN_COMMENT : field.COLUMN_NAME}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="12" class="api-make-content">
            <textarea id="editor1"></textarea>
        </el-col>
    </el-row>
@endsection

@section('footer')
    <script>
        VueInit.data.editor = "";
        VueInit.data.editor1 = "";
        VueInit.data.currentFilepath = "";
        VueInit.data.files = [];
        VueInit.data.fields = [];
        VueInit.data.allTables = [];
        VueInit.data.fileProps = {
            value: 'path',
            label: 'filename',
            children: 'children',
        };
        VueInit.data.module = null;
        VueInit.data.isIndeterminate = false;
        VueInit.data.checkAll = false;
        VueInit.data.modules = [
            {label: 'Admin', value: 'Admin'},
            {label: 'Api', value: 'Api'},
        ];
        VueInit.data.updateData = {
            table: '',
            method: '',
            service: '',
            service_filepath: '',
            controller: '',
            controller_filepath: '',
            fields: [],
            fields_info: [],
            function: null,
        };
        VueInit.event.addHandler("created:CodeMirrorInit", function () {
            this.$nextTick(() => {
                this.editor1 = CodeMirror.fromTextArea(document.getElementById('editor1'), {
                    lineNumbers: true,
                    // mode: 'application/x-httpd-php',
                    mode: 'text/x-php',
                    theme: 'material',
                    lineWrapping: true,
                    autofocus: true,
                    smartIndent: true,
                    matchBrackets: true,
                    autoCloseBrackets: true,
                });
                this.editor1.setSize('auto', '600px');
            });
        });
        VueInit.event.addHandler("created:getAllTable", function () {
            axios({
                url: "{{ sc_route([\Plugins\AdminBasic\Http\Admin\Controller\DevAuxController::class, 'getAllTables']) }}",
            }).then(({data}) => {
                if (data.code === 200) {
                    this.allTables = data.data;
                }
            })
        });

        VueInit.methods.moduleChange = function (apiModule){
            axios({
                url: "{{ sc_route([\Plugins\AdminBasic\Http\Admin\Controller\DevAuxController::class, 'apiModuleFile']) }}",
                params: {
                    module: apiModule
                },
                method: 'get'
            }).then(({ data }) => {
                this.files = data.data
            })
        }
        VueInit.methods.nodeClick = function (data){
            if (data.type === 'dir') {
                return;
            }
            if (/Service\.php$/.test(data.filename)) {
                this.updateData.service = data.filename;
                this.updateData.service_filepath = data.path;
            }else{
                this.updateData.controller = data.filename;
                this.updateData.controller_filepath = data.path;
            }
        }
        VueInit.methods.tableQuerySearch = function (query, cb) {
            let res = [];
            for (const i in this.allTables) {
                if (this.allTables[i].TABLE_NAME.includes(query) || this.allTables[i].TABLE_COMMENT.includes(query)) {
                    res.push(this.allTables[i])
                }
            }
            return cb(res);
        }
        VueInit.methods.tableSelected = function (item) {
            // this.updateData.table = item.TABLE_NAME;
            this.makeMethodName();
            axios({
                url: "{{ sc_route([\Plugins\AdminBasic\Http\Admin\Controller\DevAuxController::class, 'getTableFields']) }}",
                params: {
                    table: item.TABLE_NAME
                },
                method: 'get'
            }).then(({ data }) => {
                this.fields = data.data;
            })
        };

        VueInit.methods.handleCheckAllChange = function (val){
            this.updateData.fields = val ? this.fields.map(v => v.COLUMN_NAME) : []
            this.isIndeterminate = false
        }
        VueInit.methods.handleCheckedCitiesChange = function(value) {
            const checkedCount = value.length
            this.checkAll = checkedCount === this.fields.length
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.fields.length
        }

        VueInit.methods.makeApi = function (m) {
            let fields = [];
            for (let i = 0; i < this.fields.length; i++) {
                if(this.updateData.fields.includes(this.fields[i].COLUMN_NAME)){
                    fields.push(this.fields[i])
                }
            }
            let path;
            switch(m){
                case 'c':
                    path = this.updateData.controller_filepath;
                    break;
                case 's':
                    path = this.updateData.service_filepath;
                    break;
                default:
                    path = '';
            }

            this.updateData.fields_info = fields;
            axios({
                url: "{{ sc_route([\Plugins\AdminBasic\Http\Admin\Controller\DevAuxController::class, 'getFileContent']) }}",
                data: {
                    update: this.updateData,
                    path: path
                },
                method: 'post'
            }).then(({ data }) => {
                if(data.code === 200){
                    this.editor1.setValue(data.data.resolve);
                    if (path === '') {
                        this.$message.success('生成成功');
                    }
                }else{
                    this.$message.error(data.msg);
                }
            });
        }

        VueInit.methods.makeMethodName = function (){
            if(!this.updateData.table) return;
            if(!this.updateData.function) return;

            let pre = '{{ \App\Models\Model::getPrefix()  }}'
            let table = this.updateData.table.replace(pre, '');
            table = table.toLowerCase()
                .replace(/[-_\s](\w)/g, (_, char) => char.toUpperCase())
                .replace(/^\w/, char => char.toUpperCase());
            if(this.updateData.function === 'single'){
                this.updateData.method = 'get' + table + 'Detail';
            }else if(this.updateData.function === 'multiple'){
                this.updateData.method = 'get' + table + 'List';
            }else if(this.updateData.function === 'save'){
                this.updateData.method = 'create' + table;
            }
        }
    </script>
@endsection